package com.lsp.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * 反射类
 */
public final class ClassUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class);

    public static ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 加载类(默认初始化类)
     * @param name
     * @return
     */
    public static Class<?> loadClass(String name) {
        return loadClass(name,true);
    }

    /**
     * 加载类
     * @param className 类名
     * @param isInitialized 是否初始化
     * @return
     */
    public static Class<?> loadClass(String className, boolean isInitialized){
        Class<?> clzz;
        try {
            clzz = Class.forName(className,isInitialized,getClassLoader());
        } catch (ClassNotFoundException e) {
            LOGGER.error("load class failure", e);
            throw new RuntimeException(e);
        }
        return clzz;
    }

    public static Set<Class<?>> getClassSet(String packgeName) {
        Set<Class<?>> classSet = new HashSet<Class<?>>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packgeName.replace(".", "/"));
            while (urls.hasMoreElements()){
                URL url = urls.nextElement();
                if(url != null){
                    String protocol = url.getProtocol();
                    if(protocol.equals("file")){
                        String pakegePath = url.getPath().replace("%20", " ");
                        addClass(classSet, pakegePath, packgeName);
                    }
                }
            }
        } catch (IOException e) {
            LOGGER.error("get class set failure", e);
            throw new RuntimeException(e);
        }
        return classSet;
    }

    private static void addClass(Set<Class<?>> classSet, String pakegePath, String packgeName) {
        File[] files = new File(pakegePath).listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
            }
        });
        for(File file : files){
            String fileName = file.getName();
            if(file.isFile()){
                String className = fileName.substring(0, fileName.lastIndexOf("."));
                if(StringUtils.isNotEmpty(packgeName)){
                    className = packgeName + "." + className;
                }
                doAddClass(classSet,className);
            } else {
                String subPakegePath = fileName;
                if(StringUtils.isNotEmpty(packgeName)){
                    subPakegePath = pakegePath + "/" + subPakegePath;
                }
                String subPakegeName = fileName;
                if(StringUtils.isNotEmpty(packgeName)){
                    subPakegeName = packgeName + "." + subPakegeName;
                }
                addClass(classSet, subPakegePath, subPakegeName);
            }
        }

    }

    private static void doAddClass(Set<Class<?>> classSet, String className) {
        Class<?> loadClass = loadClass(className, false);
        classSet.add(loadClass);
    }



}
